#include <kb_radio.h>

RDA5807M radio;    ///< Create an instance of a RDA5807 chip radio

uint16_t g_block1;
bool lowLevelDebug = false;
RADIO_FREQ frequency;


// - - - - - - - - - - - - - - - - - - - - - - - - - -
/// Execute a command identified by a character and an optional number.
/// See the "?" command for available commands.
/// \param cmd The command character.
/// \param value An optional parameter for the command.
void runSerialCommand(char cmd, int16_t value)
{
  unsigned long startSeek; // after 300 msec must be tuned. after 500 msec must have RDS.
  RADIO_FREQ fSave, fLast;
  RADIO_FREQ f = radio.getMinFrequency();
  RADIO_FREQ fMax = radio.getMaxFrequency();
  char sFreq[12];
  RADIO_INFO ri;

  if (cmd == '?') {
    Serial.println();
    Serial.println("? Help");
    Serial.println("+ increase volume");//增加音量，最大15
    Serial.println("- decrease volume");//减小音量，最小0
    Serial.println("1 start scan version 1"); //向上扫描8700-10800
    Serial.println("2 start scan version 2"); //
    Serial.println(". scan up   : scan up to next sender");
    Serial.println(", scan down ; scan down to next sender");
    Serial.println("i station status");//获取频率
    Serial.println("s mono/stereo mode");
    Serial.println("b bass boost");
    Serial.println("m mute");//静音
    Serial.println("u unmute");//取消静音
    Serial.println("x debug...");
    Serial.println("* toggle i2c debug output");
    // ----- control the volume and audio output -----
  } else if (cmd == '+') {
    //增加音量
    int v = radio.getVolume();
    if (v < 15)
      radio.setVolume(++v);
  } else if (cmd == '-') {
    //降低音量
    int v = radio.getVolume();
    if (v > 0)
      radio.setVolume(--v);
  } else if (cmd == 'm') {
    //静音
    radio.setMute(true);
  } else if (cmd == 'u') {
    //取消静音
    radio.setMute(false);
  } else if (cmd == 's') {
    //切换立体声
    radio.setMono(!radio.getMono());
  } else if (cmd == 'b') {
    //增加低音
    radio.setBassBoost(!radio.getBassBoost());
  } else if (cmd == '1') {
    //搜台
    //Serial.println("Scanning all available frequencies... (1)");
    fSave = radio.getFrequency();
    // start Simple Scan: all channels
    while (f <= fMax) {
      radio.setFrequency(f);
      delay(80);
      radio.getRadioInfo(&ri);
      if (ri.tuned) {
        radio.formatFrequency(sFreq, sizeof(sFreq));
        /*Serial.print(sFreq);
        Serial.print(' ');
        Serial.print(ri.rssi);
        Serial.print(' ');
        Serial.print(ri.snr);
        Serial.print(' ');
        Serial.print(ri.stereo ? 'S' : '-');
        Serial.print(ri.rds ? 'R' : '-');
        Serial.println();*/
      } // if

      // tune up by 1 step
      f += radio.getFrequencyStep();
    } // while
    radio.setFrequency(fSave);
    //Serial.println();

  } else if (cmd == '2') {
    //Serial.println("Seeking all frequencies... (2)");
    fSave = radio.getFrequency();
    // start Scan
    radio.setFrequency(f);

    while (f <= fMax) {
      radio.seekUp(true);
      delay(100); //
      startSeek = millis();
      // wait for seek complete
      do {
        radio.getRadioInfo(&ri);
      } while ((!ri.tuned) && (startSeek + 600 > millis()));
      // check frequency
      f = radio.getFrequency();
      if (f < fLast) {
        break;
      }
      fLast = f;
      if ((ri.tuned) && (ri.rssi > 42) && (ri.snr > 12)) {
        radio.checkRDS();
        // print frequency.
        radio.formatFrequency(sFreq, sizeof(sFreq));
        //Serial.print(sFreq);
        //Serial.print(' ');

        do {
          radio.checkRDS();
          // Serial.print(g_block1); Serial.print(' ');
        } while ((!g_block1) && (startSeek + 600 > millis()));

        // fetch final status for printing
        radio.getRadioInfo(&ri);
        Serial.print(ri.rssi);
        Serial.print(' ');
        Serial.print(ri.snr);
        Serial.print(' ');
        Serial.print(ri.stereo ? 'S' : '-');
        Serial.print(ri.rds ? 'R' : '-');

        if (g_block1) {
          Serial.print(' ');
          Serial.print('[');
          Serial.print(g_block1, HEX);
          Serial.print(']');
        } // if
        Serial.println();
      } // if
    } // while
    radio.setFrequency(fSave);
    Serial.println();


  } else if (cmd == 'f') {
    frequency = value;
    radio.setFrequency(value);
  }

  else if (cmd == '.') {
    radio.seekUp(false);
  } else if (cmd == ':') {
    radio.seekUp(true);
  } else if (cmd == ',') {
    radio.seekDown(false);
  } else if (cmd == ';') {
    radio.seekDown(true);
  }
  
  // not in help:
  else if (cmd == '!') {
    if (value == 0) {
      radio.term();
    } else if (value == 1) {
      radio.init();
      radio.setBandFrequency(RADIO_BAND_FM, frequency);
    }

  } else if (cmd == 'i') {
    // info
    char s[12];
    radio.formatFrequency(s, sizeof(s));
    Serial.print("Station:");
    Serial.println(s);
    Serial.print("Radio:");
    radio.debugRadioInfo();
    Serial.print("Audio:");
    radio.debugAudioInfo();

  } else if (cmd == 'x') {
    radio.debugStatus(); // print chip specific data.

  } else if (cmd == '*') {
    lowLevelDebug = !lowLevelDebug;
    radio._wireDebug(lowLevelDebug);
  }
} // runSerialCommand()

void kb_radio_init(void)
{
    radio.init();
    frequency = 8930;
    radio.setBandFrequency(RADIO_BAND_FM, frequency);
    radio.setMono(false);
    radio.setMute(false);
    radio.setVolume(2);
}

int kb_radio_setVolume(int vol)
{
    if(vol > 15)
        vol = 15;
    else if(vol < 0)
        vol = 0;
    radio.setVolume(vol);
}

int kb_radio_getVolume(void)
{
    return radio.getVolume();
}

int kb_radio_getFrequency(void)
{
    return radio.getFrequency();
}

